/**
 * Created by Administrator on 2016/4/12.
 */
(function(){
    var loading_handler;
    function loading(v){
        var bg = v === true ? 'background-color: rgba(255,255,255,.382);':"";
        var el = '<div id="___loading" style="position:fixed;width:100%;height:100%;;top:0;left:0;z-index:999999;'+bg+'"><div class="loading circle"></div></div>';
        if(v === null){
            $("#___loading").remove();
            if(loading_handler){
                window.clearTimeout(loading_handler);
            }
        }else{
            loading_handler = setTimeout(function(){
                $('body').append(el);
            },500)
        }
    }

    window.ui = {
        loading:loading
    }
}());
(function(){
    var app = {};
    app.player_type = 2;

    app.play = function(id){
        var t = app.player_type
        var win = window.open("../player.asp?t="+t+"&progid="+id,'_blank',"menubar=no,scrollbars=no,statusbar=no,toolbar=no,resizable=yes,location=no,status=no,width=800,height=600,top="+(screen.height/2-300)+",left="+(screen.width/2-400));
        win.focus();
    }

    app.utils = (function(){
        var ut = data.ut;
        //保存服务器地址
        if(window.data && data.servers){
            var obj = {};
            for(var i in data.servers){
                obj[data.servers[i].ServerListID] = data.servers[i];
            }
            data.servers = obj;
        }

        var getHostByServer = function(server){
            if(data.servers[server]){
                var d = data.servers[server];
                if(d['ServerPos'] == 0){
                    if(ut == 0){
                        return "http://" + d["ServerHost"]+":"+d["ServerPort"];
                    }else{
                        return "http://" + location.hostname + ":" + d["ServerPort"];
                    }
                }else{
                    return  "http://" + d["ServerHost"]+":"+d["ServerPort"];
                }
            }
        }

        return {
            //处理图片路径
            'parseImage' : function(d){
                for(var i in d){
                    var t = 'assets/img/noimg.png';
                    if(d[i].PicServer && d[i].MoviePic){
                        var host = getHostByServer(d[i].PicServer);

                        if(host) t = host + "/images/vodjpg/" + d[i].MoviePic;
                    }
                    d[i].thumb = t;
                }
            },
            'getTime':function(){
                var d = new Date();
                var fix0 = function(v){ return v>=10 ? v : ('0'+v);}
                return d.getFullYear() +'年' + (d.getMonth()+1) + '月' + d.getDate() + '日' + ' 星期' + ('日一二三四五六'.charAt(d.getDay())) + ' '+fix0(d.getHours())+':'+fix0(d.getMinutes())+':'+fix0(d.getSeconds());
            },
            //获取播放器类型,实际好像没有用到
            'getPlayer' :function(ext){
                if(ext=="mkv" || ext=="vob"){
                    return 2
                }
                else -1

            }
        }
    }());

    app.bindSearch = function(){
        function search(){
            var value = $('.search input').val();
            if(value){
                var url = 'q='+value;
                $('.aside li a.select').removeClass('select');
                location.href = 'list.html#' + url;
            }
        }

        $('.search input').on('keypress', function(event){
            if(event.keyCode == "13")
            {
                search();
            }
        });

        $('.search button').on('click', function(){
            search();
        });
    }

    app.init = function(){
        app.player_type = data.playerType;
        app.user = data.user;

        $('body').on('click' , 'a.back' , function(){
            history.back();
        });

        $('body').on('click' , '.vcode' , function(){
            $(this).attr('src' , '../reg/VerifyCode.asp?'+Date.now());
        })

        $('body').on('click' , '.signout' , function(){
            ui.loading();
            $.getJSON('api.asp?a=signout' , function(rs){
                if(rs.status == '0'){
                    location.reload();
                }
            })
        });

        $('body').on('click' , '.signin.userinfo' , function(){
            if( window.confirm('确定退出') ){
                $.getJSON('api.asp?a=signout' , function(rs){
                    if(rs.status == '0'){
                        location.reload();
                    }
                })
            }
        })
        var process = function(){
            $('.time').html( app.utils.getTime());
            setTimeout(process , 1000);
        }

        process();


        if($('#j_user').length){
            var tpl_user = $('#tpl_user').html();
            $('#j_user').html( H.vm.template(tpl_user , app.user) );
        }

        var page = $('body').attr('data-page');
        if(app[page]) app[page]();

    }

    app.index = function() {
        function init() {
            var view = $('#tpl').html(),
                view_post = $('#tpl_post').html();

            app.utils.parseImage(data.latest);
            app.utils.parseImage(data.hot);
            app.utils.parseImage(data.rec);
            $('#wrap').html(H.vm.template(view, data)).fadeIn();
            $('#j_post').html(H.vm.template(view_post, data.latest[0]));

            $('.section').on('click', '.type li', function () {
                var el = $(this), type = $(this).attr("data-type");
                el.addClass('select').siblings('li').removeClass('select');
                $('.tab ul[data-type="' + type + '"]').addClass('select').siblings('ul').removeClass('select');

                $('#j_post').html(H.vm.template(view_post, data[type][0]));
            });

            app.bindSearch();
        }

        init();
    };

    app.detail = function(){
        var view = $('#tpl').html() ,
            id = H.para('id');
        app.bindSearch();
        if(id){
           /* $.ajax({
                url:'api.asp?a=detail&id='+id,
                dataType:"JSON",
                error:function(a,b,c){console.log(a,b,c)}
            });*/
            $.getJSON('api.asp',{a:'detail' , id: id} ,function(rs){

                if(rs.status == '1'){
                    app.utils.parseImage(rs.detail);
                    $('#wrap').html( H.vm.template(view , {detail:rs.detail[0] , file:rs.file}) ).fadeIn();
                }
            });
        }

        $('body').on('click' , '.play' , function(){
            var el = $(this) , id = el.attr('data-id') ,
                ext = el.attr('data-ext');
            app.play(id , ext);
        })
    }

    app.list = function(){
        var view_aside = $('#tpl_aside').html();
        var view_list = $('#tpl_list').html();


        function load(para){
            ui.loading();
            $.getJSON('api.asp',para , function(rs){
                app.utils.parseImage(rs.list);
                $('#j_list').html(H.vm.template(view_list, rs)).fadeIn();
                ui.loading(null);
            });
        }

        function search(){
            var value = $('.search input').val();
            if(value){
                var url = 'a=cat&field=MovieName&key='+encodeToGb2312(value);
                $('.aside li a.select').removeClass('select');
                load(url);
            }
        }
        /*$(window).on('hashchange' , function(){
            load(location.hash.substr(1));
        });*/

        function init(){
            $('#j_aside').html(H.vm.template(view_aside, data)).fadeIn();

            $('#j_aside').on('click' , 'li a' , function(e){
                $('.aside li a.select').removeClass('select');
                $(this).addClass('select');
                var para = $(this).attr('href').substr(1);
                load(para);
                location.hash = '';
                e.preventDefault();
            });

            $('.section').on('click' , '.nav a' , function(){
                var para = $(this).attr('href').substr(1);
                load(para);
                location.hash = '';
                e.preventDefault();
            });

            $('.search input').on('keypress', function(event){
                if(event.keyCode == "13")
                {
                    search();
                }
            });

            $('.search button').on('click', function(){
                search();
            });

            if(H.hash('q')){
                $('.search input').val(decodeURI(H.hash('q')));
                search();
            }else
                load($('.aside ul:first li:first a').addClass('select').attr('href').substr(1));
        }

        init();
    }
    
    app.sign = function(){
        var store = window.localStorage;

        $('#j_s_signup').on('click' , function () {
            $('body').addClass('up');
        });

        $('#j_s_signin').on('click' , function () {
            $('body').removeClass('up');
        });

        $('#j_signin').on('click' , function(){
            var usr = $('.in-user').val(), pwd = $('.in-pwd').val() , code = $('.in-code').val();
            if(!usr) {alert('请输入邮箱');return;}
            if(!pwd) {alert('请输入密码');return;}
            if(!code) {alert('请输入验证码');return;}

            $('#j_signin').attr('disabled','').html('登录中...');
            $.getJSON('api.asp?a=signin',{'verifycode':code,'username':usr,'userpass':pwd} , function(rs){
                if(rs.status == '0'){
                    location.href = "index.html";
                }else{
                    alert(rs.detail);
                }
                $('#j_signin').removeAttr('disabled').html('登录');
            });

            //io.send('sign.in',{username:usr,password:pwd});
        });


        $('#j_signup').on('click' , function(){
            var usr = $('.up-user').val(),
                pwd = $('.up-pwd').val(),
                pwd2 = $('.up-pwd2').val(),
                pq = $('.up-q').val(),
                pa = $('.up-a').val(),
                mode = $('.up-mode').val(),
                code = $('.up-code').val();

            if(!usr) {alert('请输入注册邮箱');return;}
            if(!pwd) {alert('请输入注册密码');return;}
            if(!pq) {alert('请输入密保问题');return;}
            if(!pa) {alert('请输入密保答案');return;}
            if(!code) {alert('请输入验证码');return;}
            if(pwd!=pwd2){alert('两次输入密码不一致');return;}
            if(pwd.length>16||pwd.length<6) {alert('密码长度6到16位');return;}

            $.getJSON('api.asp?a=signup',{'UserName':usr,'UserPass':pwd,'UserMail':usr,'PBQuestion':pq,'PBAnswer':pa,'VerifyCode':code,"PayMode":mode},function(rs){
                if(rs.status == "0"){
                    location.href = 'index.html';
                }else{
                    alert(rs.detail);
                }
                $('#j_signup').removeAttr('disabled').html('注册');

            });
            //io.send('sign.up',{username:usr,password:pwd});
        })

        $('.in-code').on('keypress', function(event){
            if(event.keyCode == "13")
            {
                $('#j_signin').trigger('click');
            }
        });

        $('.up-code').on('keypress', function(event){
            if(event.keyCode == "13")
            {
                $('#j_signup').trigger('click');
            }
        });

        if(store['USER.NAME']) $('.in-user').val(store['USER.NAME']);
    }

    app.init();
}());